package io.yuanqi.hgtcshop.controller;

import com.alibaba.fastjson.JSONObject;
import io.yuanqi.hgtcshop.config.RedisService;
import io.yuanqi.hgtcshop.entity.dos.Member;
import io.yuanqi.hgtcshop.entity.security.Token;
import io.yuanqi.hgtcshop.entity.vo.ResultMessage;
import io.yuanqi.hgtcshop.service.MemberService;
import io.yuanqi.hgtcshop.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Collections;

@Slf4j
@RestController
@RequestMapping("/wx")
public class WeChatController {


    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.secret}")
    private String secret;
    @Value("${isXy}")
    private Boolean isXy;

    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisService redisService;


    /**
     * 网页授权
     * 通过code换取网页授权access_token（该AccessToken与基础AccessToken不一样）
     */
    public final static String WEB_GET_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    /**
     * 网页授权
     * 获取用户详细信息（scope为 snsapi_userinfo）
     */
    public final static String WEB_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    @RequestMapping(value = "/getWxInfoByCode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultMessage<JSONObject> getWxInfoByCode(@RequestParam(value = "code") String code) {
        JSONObject resultObj = new JSONObject();
        String url = WEB_GET_ACCESS_TOKEN.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);
        log.info("WEB_GET_ACCESS_TOKEN:{}", url);
        JSONObject accessTokenObj = getJsonData(url);
        log.info("accessTokenObj={}", accessTokenObj);
        if (accessTokenObj != null && accessTokenObj.get("access_token") != null) {
            String accessToken = accessTokenObj.getString("access_token");
            String openId = accessTokenObj.getString("openid");
            log.info("accessToken:{} openId:{}", accessToken, openId);
//            if (accessToken != null) {
//                String webGetUserInfoUrl = WEB_GET_USER_INFO.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
//                log.info("webGetUserInfoUrl:{}", webGetUserInfoUrl);
//                resultObj = getJsonData(webGetUserInfoUrl);
//                log.info("resultObj:{}", resultObj);
//                // 获取用户信息
//            }

            resultObj.put("openid",openId);
            resultObj.put("nickname","临时用户");
            resultObj.put("sex","未知");
            resultObj.put("province","province");
            resultObj.put("city","city");
            resultObj.put("country","country");
            resultObj.put("headimgurl","https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46");
            resultObj.put("privilege","PRIVILEGE1");
            resultObj.put("unionid","o6_bmasdasdsad6_2sgVt7hMZOPfL");

            if (isXy) {
                // 模拟注册用户，根据当前人的openId
                Member byMobile = memberService.findByMobile(openId);
                if (null == byMobile) {
                    memberService.register(resultObj);
                }
            }
        }
        // 根据openId注册用户
        return ResultUtil.data(resultObj);
    }


    @RequestMapping(value = "/getWxInfoByOpenId", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultMessage<Member> getWxInfoByOpenId(@RequestParam(value = "openId") String openId) {
        log.info(".getWxInfoByOpenId openId:{}", openId);
        Member member = memberService.findByOpenId(openId);
        log.info(".getWxInfoByOpenId member:{}", JSONObject.toJSONString(member));
        return ResultUtil.data(member);
    }


    /**
     * 发起get请求
     *
     * @param url
     * @return
     */
    public JSONObject getJsonData(String url) {
        RestTemplate restTemplate = new RestTemplate();
        // 设置 HTTP 头部信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept-Charset", "UTF-8");
        // 创建 StringHttpMessageConverter 并设置编码方式为 UTF-8
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        stringHttpMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
        restTemplate.getMessageConverters().add(0, stringHttpMessageConverter);
        // 发送 GET 请求，并将响应映射为 JSONObject
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        // 获取响应中的 JSONObject
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        return jsonObject;
    }

}